<?php
namespace control;

/*
*部门类
*/

class departmentClass extends adIndexClass
{
    private const page = 'department'; # 权限
    private const table = 'department'; # 数据表
    private const title = '部门';

    /**
     * 获取分类名称
     * @param $id
     * @return mixed
     */
    public static function getTypeName($id): mixed
    {
        $type = query(self::table, "id = '$id'");
        if (!empty($type['pid'])) {
            $result = self::getTypeName($type['pid']);
            $name = $result . '->' . $type['name'];
        } else {
            $name = $type['name'] ?? null;
        }
        return $name;
    }

    public static function getDepartmentAll($data = []): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail(this,'" . self::page . "')";
        //当前层级
        $data['level'] = isset($data['level'])?$data['level']+1:0;
        // 结果
        $result = find(['table' => 'department', 'field' => 'id,name', 'where' => $data['where'] . " order by list asc"]);
        $style = ($data['where'] == "pid='0'" || $data['level'] == 0) ? '' : " class='child-node' data-level='{$data['level']}' ";
        $temp = "<ul {$style} {$data['where']}>";
        // 角标
        $lastone = lastone;
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 角标
                $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $has = query('department', $data['where']);
                if ($has['id']) {
                    $temp .= "<li class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">{$arrow}<span class='textcontent'>{$textcontent_ico}{$value['name']}</span></li>";
                    $temp .= self::getDepartmentAll($data);
                } else {
                    $temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' onclick=\"{$data['click']}\">{$lastone}<span class='textcontent'>{$textcontent_ico}{$value['name']}</span></li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option = [];
        if ($this->post('type') == 'job') {
            $option['click'] = 'replaceContent(this, \'job\')';
        }
        $json['html'] = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }


    public function homeHtml(): string
    {
        $all = self::getDepartmentAll();
        $title = L('department.other.no_department');
        $rightHtml = $html = <<<EOT
            <div class="container-no">
                <img class="container-no-img" src="{$this->root}img/control/department-no.svg">
                <p class="center gray">$title</p>
            </div>
EOT;
        return  componentClass::leftNav([
            'title'=>L('department.search.title'),
            'button'=>"<img class='tool-img' title='".L('department.button.edit')."' onclick=\"layer('" . self::page . "','edit',{pid: 0})\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
    }

    /*列表页-查询条件*/
    public function home()
    {
        //返回
        return $this->homeFun($this->homeHtml());
    }


    /*编辑部门基本资料-弹出层*/
    public function edit()
    {
        $id = $this->post('id') ?: suiji();
        //数据查询
        $info = query(self::table, " id = '" . $id . "' ");

        $pid = $info['pid'] ?: ($this->post('pid') ?? 0);
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('department.table.deparment_name') . "：" => text(["name" => "name", "value" => $info['name'], 'class' => 'text']),
                    L('department.table.department_manager') . "：" => selectMultiple(['table' => 'staff', "title" => L('department.table.department_manager'), 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'value' => $info['manager']]),
                ],
                [
                    L('department.table.list') . "：" => text(["name" => "list", "value" => $info['list'], 'class' => 'text']) . hidden(['name' => 'pid', 'value' => $pid]),
                ]
            ]
        ]);
        //返回
        return $this->layer(["title" => L('department.layer.title'), "height" => 220, 'winFix' => true, "html" => $html]);
    }

    /*部门基本信息-异步处理*/
    public function editEdit()
    {
        $id = $this->post('id') ?: suiji();
        //赋值
        $field = [
            'pid' => $this->post('pid') ?? 0,
            "name" => $this->post('name'),      //部门名称
            'manager' => $this->post('manager'),
            "list" => $this->post('list'),      //排序号
        ];
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('department.edit.permission_edit_warn');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('department.edit.department_name_warn');
        } elseif (sqlNum("department", "pid = '$field[pid]' and name = '$field[name]' and id != '" . $id . "' ") > 0) {
            $json['warn'] = L('department.edit.department_repeat_warn');
        } elseif (empty($id)) {
            $json['warn'] = L('department.edit.department_id_warn');
        } elseif (empty($info['id'])) {
            $userNo = codeTemplateClass::generateCode(self::page, [
                'prefix' => 'DP',
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ], $field);
            $field['orderNo'] = $userNo;
            $field = array_merge($field, ["id" => $id, 'stid' => self::$stid, "time" => $this->time]);

            $json['warn'] = insert(["table" => self::table, "field" => $field]);
        } else {
            $json['warn'] = update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $field['name']], L('department.other.department_edit_log'));
            $this->logText(array("type" => "department", "text" => $text));
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    public
    function detail()
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $json['warn'] = L('department.detail.permission_see_warn');
        } elseif (empty($this->post('id'))) {
            $json['warn'] = L('department.edit.department_id_warn');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('department.detail.find_none_department');
        } else {
            $data = [
                "id" => $info['id'],
                "title" => $info['name'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => L('department.button.editor'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name" => L('department.button.addSibling'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => suiji(), 'pid' => $info['pid']],
                ];
                $button[] = [
                    "name" => L('department.button.addNext'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => suiji(), 'pid' => $info['id']],
                ];
                $button[] = [
                    "name" => L('department.button.delete'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "delete",
                    "post" => ["id" => $info['id']],
                ];
            }
            $button = $this->tableShowButton($button);
            //生成表单
            $table = $this->tableShow([
                [
                    [
                        L('department.table.deparment_name') => $info['name'],
                        L('department.table.department_manager') => self::findStaff($info['manager']),
                        L('department.table.orderNo') => $info['orderNo'],
                        L('department.table.list') => $info['list'],
                    ],
                    [
                        L('department.table.creator') => self::findStaff($info['stid']),
                        L('department.table.updateTime') => $info['updateTime'],
                        L('department.table.creatTime') => $info['time'],
                    ]
                ]
            ]);
            $json['html'] = "
            <div class='tab-box'>
                    <div class='tab-button'>" . $button . "</div>
                    <div class='tab-content'>
                    " . $table . clear . "
                    </div>
            </div>";
            //生成页面
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-部门管理-删除部门*/
    public
    function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('department.detail.permission_delete_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('department.detail.none_data_is_choosed');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if (!$this->juageDel($id)) {
                        $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $id], L('department.other.department_child')) . "<br>";
                        continue;
                    }
                    //递归删除
                    $this->deleteAll($id);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $id], L('department.other.department_del_log')) . "<br>";
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('department.other.department_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }

    private
    function juageDel($id): bool
    {
        $bool = true;
        $material_type = query('department', "pid = '$id'");
        if ($material_type['id']) {
            $bool = $this->juageDel($material_type['id']);
        }
        if (static::total(array('table' => 'job', 'where' => "departmentId = '$id'")) > 0) {
            return false;
        }
        return $bool;
    }

    public
    function deleteAll($id)
    {
        $material_type = query(self::table, "pid = '$id'");
        if ($material_type['id']) {
            $this->deleteAll($material_type['id']);
        }
        delete(array('table' => self::table, 'where' => "id = '$id'"));
    }
}
